package cn.iwangwei.demo;

import sun.security.util.BitArray;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * @author wangwei
 * @since 1.0
 */
public class Chromosome {

    private String code;

    private double adaptation;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public double getAdaptation() {
        return adaptation;
    }

    public void setAdaptation(double adaptation) {
        this.adaptation = adaptation;
    }

    private static Chromosome generateRandomly() {
        Chromosome chromosome = new Chromosome();

        int codeValue = new Random().nextInt(510) + 1;
        String binaryString = Integer.toBinaryString(codeValue);
        if (binaryString.length() < 9) {
            int differential = 9 - binaryString.length();
            for (int i = 0; i < differential; i++) {
                binaryString = "0" + binaryString;
            }
        }

        chromosome.code = binaryString;
        chromosome.adaptation = getAdaptation(binaryString);

        return chromosome;
    }

    @Override
    public String toString() {
        return "Chromosome{" + "code='" + code + '\'' + ", adaptation=" + adaptation + '}';
    }

    private static double getAdaptation(String binaryString) {
        int value = Integer.valueOf(binaryString, 2);

        return -Math.pow(value / 100.0, 2) + 3;
    }

    public static void main(String[] args) {
        List<Chromosome> chromosomes = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            chromosomes.add(Chromosome.generateRandomly());
        }

        chromosomes = chromosomes.stream().sorted((c1, c2) -> (int) (c2.adaptation * 100 - c1.adaptation * 100)).collect(Collectors.toList());

        chromosomes.forEach(c -> System.out.println(c));

        chromosomes = chromosomes.subList(0, 80);

        chromosomes.forEach(c -> System.out.println(c));
    }
}
